// 这个reducer只负责管理购物车
import { Toast } from 'antd-mobile'
function shopReducer(state = [], action = { type: '', payload: null }) {
    let newstate = JSON.parse(JSON.stringify(state));

    if (action.type == 'SHOPADD') {
        var index = newstate.findIndex((item) => {
            return item.id == action.payload.id;
        })

        if (index != -1) { //该商品已经在购物车中
            newstate[index].count++;
        } else { //该商品是第一次加入购物车中
            //深拷贝商品对象, 对深拷贝的对象添加count属性, 值为1
            var good = JSON.parse(JSON.stringify(action.payload))
            good.count = 1;
            newstate.push(good)
        }
        return newstate;
    } else if (action.type == 'SHOPSUB') {
        var index = newstate.find((item) => {
            return item.id == action.payload.id;
        })
        if (index.count > 1) {
            index.count--
            console.log(index.count)
        } else {
            Toast.show({
                content: '宝贝的数量不能再减少了',
                afterClose: () => {
                    console.log('after')
                },
            })
        }



        return newstate;
    } else if (action.type == 'SHOPCLEAR') {
        newstate = [];
        return newstate;
    } else if (action.type == 'SHOPEDIT') {

        newstate = action.payload
        return newstate;
    } else {
        return state
    }


}
//无名导出
export default shopReducer